package com.xiaov.android.games.sounds;

import java.io.IOException;
import java.util.HashMap;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;

public class Util {
	
	private static Context context;
	
	private static MediaPlayer mp;
	
	public static void playBGM(String path, boolean looping) {
		if(mp == null) {
			mp = new MediaPlayer();
		}
		mp.reset();
		try {
			mp.setDataSource(path);
			mp.prepare();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mp.setLooping(looping);
		mp.start();
	}
	
	public static void stopBGM() {
		if(mp != null) {
			mp.release();
			mp = null;
		}
	}
	
	private static int MAX_CHANNEL = 6;
	private static SoundPool soundPool;
	private static HashMap<String, Integer> soundPoolMap;
	private static AudioManager audioManager;
	
	public static void playSE(String path, float volume, int loop, float rate) {
		if(soundPool == null) {
			soundPool = new SoundPool(MAX_CHANNEL, AudioManager.STREAM_MUSIC, 10);
		}
		
		if(soundPoolMap == null) {
			soundPoolMap = new HashMap<String, Integer>();
		}
		
		if(!soundPoolMap.containsKey(path)) {
			soundPoolMap.put(path, soundPool.load(path, 1));
		}
		
		if(volume < 0) {
			if(audioManager == null)
				audioManager = (AudioManager)context
					.getSystemService(Context.AUDIO_SERVICE);
			volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		}
		
		while(soundPool.play(soundPoolMap.get(path),
				volume, volume, 0, loop, rate) == 0);
	}
	
	public static void playSE(String path) {
		playSE(path, -1f, 0, 1f);
	}
	
	public void stopSE(String path) {
		if(soundPool != null && soundPoolMap != null
				&& soundPoolMap.containsKey(path)) {
			soundPool.stop(soundPoolMap.get(path));
		}
	}

}
